<!-- 实验页面代码 -->

<template>
  <div
    style="height: 100%; width: 100%"
    ref="reflayoutContainercontainer"
  ></div>
</template>

<script>
import {
  Layout as LayoutDHX,
  Tree as TreeDHX,
  Tabbar as TabbarDHX,
  Toolbar as ToolbarDHX,
  Window as WindowDHX,
  Form as FormDHX,
  confirm as ConfirmDHX,
  TreeCollection,
  // ContextMenu as CMenuDHX,
} from 'dhx-suite-package';
import LayoutComposer from '@/components/composer/layoutComposer';
import { Message, Alert } from '@/components/message';
import { mapActions } from 'vuex';

export default {
  name: 'ComposerBase',
  data: () => ({
    barHeight: 37,
    defaultContent: 'qreg Q[4];\n',

    // 0. 整体框架
    layoutContainer: null,

    // 1. 左侧边栏
    toolbarFile: null,
    treeFile: null,
    datatreeFile: new TreeCollection(),
    activeFile: null,
    windowFile: null,
    formFile: null,
    windowRename: null,
    formRename: null,
    // cmenuFile: null,

    // 2. 右侧
    // 2.1. tabbar标签页
    tabbarPage: null,
    // 2.2. 标签页里的LayoutComposer
    layoutPage: null,
  }),
  mounted() {
    this.init();
  },
  methods: {
    ...mapActions('fileModule', ['fcreate', 'fsave', 'frename', 'flist', 'fload', 'fdelete']),
    init() {
      // 初始化
      this.layoutContainer = this.layoutContainer_create(
        this.$refs.reflayoutContainercontainer,
      );
      // 1. 左侧
      this.toolbarFile = this.toolbarFile_create();
      this.treeFile = this.treeFile_create();
      this.windowFile = this.windowFile_create();
      this.formFile = this.formFile_create();
      // this.cmenuFile = this.cmenuFile_create();
      this.windowRename = this.windowRename_create();
      this.formRename = this.formRename_create();
      // 2. 右侧
      this.tabbarPage = this.tabbarPage_create();

      // 事件
      this.toolbarFile_event();
      this.treeFile_event();
      this.formFile_event();
      // this.cmenuFile_event();
      this.formRename_event();
      // 右侧
      this.tabbarPage_event();

      // reload
      this.treeFile_reload(); // 加载文件树

      // 挂载
      this.windowFile.attach(this.formFile);
      this.windowRename.attach(this.formRename);
      this.layoutContainer.getCell('toolbarFile').attach(this.toolbarFile);
      this.layoutContainer.getCell('treeFile').attach(this.treeFile);
      this.layoutContainer.getCell('tabbarPage').attach(this.tabbarPage);
      this.layoutContainer_reload(null);

      return this.layoutContainer;
    },

    // 0. 整体框架 //////////////////////////////////////
    layoutContainer_create(ref) {
      const mylayout = new LayoutDHX(ref, {
        type: 'line',
        cols: [
          {
            width: '13%',
            collapsable: true,
            resizable: true,
            rows: [
              { id: 'toolbarFile', height: this.barHeight },
              { id: 'treeFile', height: 'content' },
            ],
          }, {
            rows: [
              { id: 'tabbarPage', height: this.barHeight },
              {
                id: 'layoutPage',
                height: document.documentElement.clientHeight - 57 - this.barHeight,
              },
            ],
          },
        ],
      });
      return mylayout;
    },
    // 重载可视化部分
    layoutContainer_reload(page) {
      if (page == null) {
        this.layoutContainer.getCell('layoutPage').attachHTML('<h3>&emsp;请选择文件</h3>');
      } else {
        this.layoutContainer.getCell('layoutPage').attach(page);
      }
    },
    // 1. 左侧 /////////////////////////////////////////
    // 1.1. 工具栏
    toolbarFile_create() {
      const mytoolbar = new ToolbarDHX('toolbarFile', {
        navigationType: 'pointer',
        data: [
          {
            id: 'createFile',
            html: '<i class="fa-solid fa-file-circle-plus"></i>',
            tooltip: '新建',
          }, {
            type: 'separator',
          }, {
            type: 'spacer',
          }, {
            id: 'renameFile',
            html: '<i class="fa-solid fa-pen"></i>',
            tooltip: '重命名',
          }, {
            id: 'deleteFile',
            html: '<i class="fa-solid fa-trash"></i>',
            tooltip: '删除',
          },
        ],
        css: 'toolbar_style',
      });
      return mytoolbar;
    },
    // 新建 | 重命名，删除
    toolbarFile_event() {
      const that = this;
      const mytoolbar = that.toolbarFile;
      mytoolbar.events.on('click', (id) => {
        switch (id) {
          case 'createFile':
            // 弹出输入输入文件名=>formFile_event
            this.windowFile.show();
            break;
          case 'renameFile':
            if (that.activeFile == null) {
              Alert('请选择需要重命名的文件');
            } else { // =>formRename_event
              that.windowRename.show();
            }
            break;
          case 'deleteFile':
            if (that.activeFile == null) {
              Alert('请选择需要删除的文件');
            } else {
              // 弹窗确认删除
              ConfirmDHX({
                text: `您确定要删除文件“${that.activeFile.value}”吗？`,
                buttons: ['取消', '确定'],
                css: 'message_style',
              }).then((res) => {
                if (res) { // 确定
                  // 删除文件
                  const formState = {};
                  formState.id = that.activeFile.id;
                  this.fdelete(formState).then(() => {
                    Message('删除成功');
                    that.treeFile_reload(); // 更新文件树
                    that.tabbarPage_delete(formState.id); // 更新tabbar
                  }).catch((err) => { Alert(err.response.data.msg); });
                }
              });
            }
            break;
          default: break;
        }
      });
    },
    // 1.2. 文件树
    treeFile_create() {
      const mytree = new TreeDHX('treeFile', {
        editable: true,
        itemHeight: 30,
        data: this.datatreeFile,
      });
      return mytree;
    },
    treeFile_event() {
      const that = this;
      const myevents = that.treeFile.events;
      // 点击文件，记录活跃文件，打开标签页
      myevents.on('itemClick', (id) => {
        // eslint-disable-next-line no-underscore-dangle
        that.activeFile = that.datatreeFile._pull[id];
        if (that.tabbarPage.getCell(id) == null) {
          // 打开tab，并设置active
          that.tabbarPage.addTab({
            id,
            tab: that.activeFile.value,
            tabCss: 'tab_style',
          });
        }
        that.tabbarPage.setActive(id);
        if (that.layoutPage == null) {
          that.layoutPage = LayoutComposer.init();
          that.layoutContainer_reload(that.layoutPage);
        }
      });
    },
    treeFile_reload() {
      const that = this;
      // 从数据库中获取用户的文件列表
      this.flist().then((res) => {
        if (res.data.data.files == null) {
          Message('未创建文件');
          that.layoutContainer_reload(null);
        } else {
          // 加载文件树
          const mydata = res.data.data.files;
          that.datatreeFile.parse(mydata);
          Message('文件列表刷新成功');
        }
      }).catch((err) => {
        Alert(err.response.data.msg);
      });
      // 挂载文件右键菜单
      // document.querySelector('.dhx_tree').oncontextmenu = (e) => {
      //   e.preventDefault();
      //   that.cmenuFile_reload(e);
      // };
    },
    // 1.3. 文件命名弹窗
    windowFile_create() {
      const mywindow = new WindowDHX({
        modal: true,
        title: '新建线路',
        closable: true,
        width: 360,
        height: 220,
      });
      return mywindow;
    },
    formFile_create() {
      const myform = new FormDHX('formFile', {
        rows: [
          {
            type: 'input',
            id: 'name',
            required: true,
            hiddenLabel: true,
            placeholder: '请输入文件名',
            errorMessage: '文件名不能为空',
          }, {
            align: 'center',
            cols: [
              {
                type: 'button',
                id: 'send',
                text: '确认',
                submit: true,
                full: true,
              },
            ],
          },
        ],
      });
      return myform;
    },
    // 创建新文件
    formFile_event() {
      const that = this;
      const myform = that.formFile;
      myform.getItem('send').events.on('click', () => {
        // 判断表单是否合法
        if (myform.validate()) {
          // 获取文件名和文件内容
          const formState = myform.getValue();
          formState.content = that.defaultContent;
          // 创建文件
          this.fcreate(formState).then(() => {
            Message('创建成功');
            that.treeFile_reload(); // 调用flist更新文件树
            that.windowFile.hide(); // 关闭表单弹窗
          }).catch((err) => {
            Alert(err.response.data.msg);
          });
        }
      });
    },
    // // 1.4. 右键菜单
    // cmenuFile_create() {
    //   const mycmenu = new CMenuDHX('cmenuFile', {
    //     css: 'dhx_widget--bordered',
    //     data: [
    //       { // 重命名文件
    //         type: 'menuItem',
    //         id: 'rename',
    //         value: '重命名',
    //         icon: 'mdi mdi-pencil',
    //       }, { // 删除文件
    //         type: 'menuItem',
    //         id: 'delete',
    //         value: '删除',
    //         icon: 'mdi mdi-delete',
    //       },
    //     ],
    //   });
    //   return mycmenu;
    // },
    // cmenuFile_event() {
    //   const that = this;
    //   const myevents = that.cmenuFile.events;
    //   myevents.on('click', (id) => {
    //     switch (id) {
    //       case 'rename':
    //       case 'delete':
    //         break;
    //       default: break;
    //     }
    //   });
    // },
    // cmenuFile_reload(e) {
    //   this.cmenuFile.showAt(e);
    // },
    // 1.5. 文件重命名弹窗
    windowRename_create() {
      const mywindow = new WindowDHX({
        modal: true,
        title: '重命名',
        closable: true,
        width: 360,
        height: 220,
      });
      return mywindow;
    },
    formRename_create() {
      const myform = new FormDHX('formRename', {
        rows: [
          {
            type: 'input',
            id: 'name',
            required: true,
            hiddenLabel: true,
            placeholder: '请输入新文件名',
            errorMessage: '文件名不能为空',
          }, {
            align: 'center',
            cols: [
              {
                type: 'button',
                id: 'send',
                text: '确认',
                submit: true,
                full: true,
              },
            ],
          },
        ],
      });
      return myform;
    },
    // 重命名文件
    formRename_event() {
      const that = this;
      const myform = that.formRename;
      myform.getItem('send').events.on('click', () => {
        // 判断表单是否合法
        if (myform.validate()) {
          // 获取文件ID，文件名
          const formState = myform.getValue();
          formState.id = that.activeFile.id;
          // 更新文件名
          this.frename(formState).then(() => {
            Message('更新成功');
            that.windowRename.hide();
            that.treeFile_reload(); // 更新文件树
            that.tabbarPage_rename(formState.id, formState.name); // 更新tabbar
          }).catch((err) => {
            Alert(err.response.data.msg);
          });
        }
      });
    },

    // 2. 右侧 /////////////////////////////////////////
    tabbarPage_create() {
      const mytabbar = new TabbarDHX('tabbarPage', {
        tabHeight: this.barHeight - 1,
        tabWidth: 150,
        closable: true,
      });
      return mytabbar;
    },
    // tab切换，保存
    tabbarPage_event() {
      const that = this;
      const mytabbar = that.tabbarPage;
      // a. 切换tab
      mytabbar.events.on('change', (id, prev) => {
        if (prev == id) { return; }
        const formState = {};
        // a. 保存旧页面的代码
        if (prev != null) {
          // 获取文件ID和代码内容
          formState.id = prev;
          formState.content = LayoutComposer.richtextCode_get();
          // 保存文件
          // eslint-disable-next-line no-underscore-dangle
          const fname = that.datatreeFile._pull[prev].value;
          this.fsave(formState).then(() => { Message(`保存${fname}成功`); })
            .catch((err) => { Alert(err.response.data.msg); });
        }
        // b. 加载新页面的代码
        formState.id = id;
        formState.content = null;
        this.fload(formState).then((res) => {
          LayoutComposer.richtextCode_set(res.data.data.file.content);
        }).catch((err) => {
          console.log(err);
          Alert(err.response.data.msg);
        });
        // eslint-disable-next-line no-underscore-dangle
        const fname = that.datatreeFile._pull[id].value;
        LayoutComposer.activeFile.name = fname; // 设置页面名字
        LayoutComposer.activeFile.id = id; // 设置页面id
        // LayoutComposer.fcompile(); // TODO：是否自动编译
      });
      // b. 关闭tab
      mytabbar.events.on('afterClose', (id) => {
        // 关闭唯一的活跃页不会触发change event，需要单独保存文件
        if (mytabbar.getActive() == null) {
          // a. 保存文件
          const formState = {};
          formState.id = id;
          formState.content = LayoutComposer.richtextCode_get();
          // eslint-disable-next-line no-underscore-dangle
          const fname = that.datatreeFile._pull[id].value;
          this.fsave(formState).then(() => { Message(`保存${fname}成功`); })
            .catch((err) => { Alert(err.response.data.msg); });
          // b. 取消挂载可视化页面
          that.layoutContainer_reload(null);
        }
      });
    },
    // 重命名tab
    tabbarPage_rename(id, name) {
      const that = this;
      // 如果重命名的文件在tab上，刷新tabbar
      if (that.tabbarPage.getCell(id) != null) {
        that.tabbarPage.getCell(id).config.tab = name;
        that.tabbarPage.paint();
      }
      // 如果重命名的文件是活跃tab，重新设置页面名字
      if (that.tabbarPage.getActive() == id) {
        LayoutComposer.activeFile.name = name; // 设置页面名字
      }
    },
    // 删除tab
    tabbarPage_delete(id) {
      const that = this;
      if (that.tabbarPage.getCell(id) != null) {
        that.tabbarPage.removeTab(id);
      }
    },
  },
};
</script>
